import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Practice3 {
//    144. 二叉树的前序遍历
//    二叉树前序非递归遍历实现
    public List<Integer> preorderTraversal(TreeNode root) {
//        list存放前序遍历后的元素
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.empty()) {
//            先理解内层while  再去理解外层的while
            while (cur != null) {
                stack.push(cur);
//                System.out.println(cur.val+" ");
                list.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }




//    二叉树中序非递归遍历实现
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
//            System.out.println(cur.val+" ");
            list.add(top.val);
            cur = top.right;
        }
        return list;
    }


//    二叉树中序非递归遍历实现  (需要多考虑一个点)
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode pre = null;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.peek();
//            top.right == pre这个条件防止s循环   防止pop后又push导致s循环
//            如果当前节点的右子树被打印过 那么就可以直接弹出了
            if (top.right == null || top.right == pre) {
                stack.pop();
//            System.out.println(cur.val+" ");
                list.add(top.val);
                pre = top;
            }else {//top.right ！= null
                cur = top.right;// 进行右子树进行while循环 看左右子树是否为空
            }
        }
        return list;
    }

//    剑指 Offer 27. 二叉树的镜像//翻转二叉树
//    1.
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) return null;
        TreeNode left = mirrorTree(root.left);
        TreeNode right = mirrorTree(root.right);
        root.left = right;
        root.right =left;
        return root;
    }
//    2.
    public TreeNode mirrorTree2(TreeNode root) {
        if (root == null) return null;
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        mirrorTree(root.left);
        mirrorTree(root.right);
        return root;
    }
}
